package com.gy.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gy.controller.common.UploadController;
import com.gy.controller.common.UserHolder;
import com.gy.entity.result.Author;
import com.gy.entity.result.Papers;
import com.gy.mapper.PapersMapper;
import com.gy.query.PapersQuery;
import com.gy.result.Result;
import com.gy.service.PapersService;
import com.gy.utils.AliOSSUtils;
import com.gy.vo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class PapersServiceImpl extends ServiceImpl<PapersMapper, Papers> implements PapersService {
    @Autowired
    private AliOSSUtils aliOSSUtils;

    @Autowired
    private PapersMapper papersMapper;

    @Autowired
    private UploadController uploadController;
    @Autowired
    private UserServiceImpl userService;
    @Override
    @Transactional
    public Result savePapers(Papers papers) {
        if (papers == null) {
            log.warn("传入的论文对象为空");
            return Result.error("论文对象不能为空");
        }
        try {
            List<String> indexing = papers.getIndexing();

            papers.setIndexing(indexing);
            // 设置用户 ID
            papers.setUserId(UserHolder.getUser().getUserId());

            boolean save = papersMapper.savePapers(papers);
            if (!save) {
                return Result.error("新增失败");
            }
            userService.incrementUserPaperCount();

            return Result.success("新增成功");
        } catch (Exception e) {
            // 记录异常日志
            log.error("保存论文时发生异常", e);
            return Result.error("系统错误，请稍后再试");
        }
    }

    @Override
    @Transactional
    public Result savePapers(Papers papers, Long userId) {

        if (papers == null) {
            log.warn("传入的论文对象为空（显式传userId场景）");
            return Result.error("论文对象不能为空");
        }

        if (userId == null) {
            log.error("显式传递的userId为空，无法新增论文");
            return Result.error("用户身份无效");
        }
        try {

            List<String> indexing = papers.getIndexing();
            papers.setIndexing(indexing);

            papers.setUserId(userId);

            boolean save = papersMapper.savePapers(papers);
            if (!save) {
                return Result.error("新增失败");
            }

            userService.incrementUserPaperCount(userId);

            return Result.success("新增成功");
        } catch (Exception e) {

            return Result.error("系统错误，请稍后再试");
        }
    }



    /**
     * 根据openid查询某个人的论文信息
     * @return
     */
    @Override
    public  Result<PageVO<Papers>> getPapers(PapersQuery papersQuery) {
        Long openId = UserHolder.getUser().getUserId();

        Page<Papers> page = Page.of(papersQuery.getPageNo(), papersQuery.getPageSize());

        // 排序条件
        if (!papersQuery.getSortBy().isEmpty() || papersQuery.getIsAsc() != null) {
            page.addOrder(new OrderItem(papersQuery.getSortBy(), papersQuery.getIsAsc()));
        } else {
            // 为空，默认按照出版时间排序
            page.addOrder(new OrderItem("id", false));
        }

        // 构建查询条件
        LambdaQueryChainWrapper<Papers> queryWrapper = lambdaQuery().select()
                .eq(openId != null, Papers::getUserId, openId);

        // 仅在开始日期和结束日期不为空且有效时添加 between 条件
        if (papersQuery.getStartDate() != null && papersQuery.getEndDate() != null) {
            try {
                Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse(papersQuery.getStartDate());
                Date endDate = new SimpleDateFormat("yyyy-MM-dd").parse(papersQuery.getEndDate());
                queryWrapper.between(Papers::getPublishDate, startDate, endDate);
            } catch (ParseException e) {
                // 处理日期解析错误
                System.err.println("Invalid date format: " + e.getMessage());
            }
        }

        //添加个人排名参数查询
        if (papersQuery.getAuthorRank() != null) {
            queryWrapper.eq(Papers::getAuthorRank, papersQuery.getAuthorRank());
        }

        // 执行分页查询
        Page<Papers> p = queryWrapper.page(page);

        // 封装VO结果
        PageVO<Papers> vo = new PageVO<>();
        vo.setTotal(p.getTotal());
        vo.setPages(p.getPages());
        List<Papers> records = p.getRecords();
        if (CollUtil.isEmpty(records)) {
            vo.setList(Collections.emptyList());
        }
        //3.4拷贝
        vo.setList(records);
        //4.返回
        return Result.success(vo);
    }




    /**
     * 根据论文id删除论文
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Result removePapersById(Long id) {
        Papers papers = getById(id);
        if (papers == null) {
            return Result.error("论文未找到");
        }

        String pdfPath = papers.getPdfPath();

        // 检查 pdfPath 是否为空
        if (pdfPath != null && !pdfPath.isEmpty()) {
            try {
                uploadController.deleteFile(pdfPath);
            } catch (Exception e) {
                return Result.error("删除文件失败");
            }
        } else {
            log.warn("pdfPath 为空，无需删除文件");
        }

        boolean removed = removeById(id);
        if (!removed) {
            return Result.error("删除论文失败");
        }
        userService.decrementUserPaperCount();
        return Result.success("论文删除成功");
    }



    @Override
    public Papers getPapersById(Long id) {
        if (id == null) {
            return null;
        }
        return papersMapper.selectPaperById(id);
    }

    /**
     * 更改论文信息
     * @param papers
     * @return
     */
    @Override
    public Result updatePapers(Papers papers) {
        // 参数验证
        if (papers == null) {
            return Result.error("论文信息不能为空");
        }
        if (papers.getId() == null) {
            return Result.error("论文ID不能为空");
        }

        try {
            int affectedRows = papersMapper.updatePapers(papers);
            if (affectedRows > 0) {
                return Result.success(papers);
            } else {
                return Result.error("未找到对应的论文信息进行更新");
            }
        } catch (Exception e) {
            // 记录日志
            log.error("更新论文信息时发生异常", e);
            return Result.error("更新论文信息失败");
        }
    }

    /**
     * 通过多个id，查询多个论文信息
     * @param ids
     * @return
     */
    @Override
    public Result getPapersByIds(Long[] ids) {
        if (ids != null && ids.length > 0) {
            List<Papers> papersList = papersMapper.selectPaperBatchIds(Arrays.asList(ids));
            return Result.success(papersList);
        }
        return null;
    }


}
